from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget,QTableWidgetItem
from PyQt5.QtCore import QObject, pyqtSignal,Qt
from m_ui import Ui_MainWindow
from sys import argv,exit
from winsound import Beep
from tqsdk import TqApi, TqAuth,TqSim
from threading import Thread
from datetime import datetime
from time import time
from handleKline import startegyHandle
from canvas import KlineCanvas
from tool.handleData import get_exchange,nanoseconds_timestamp_to_datetime,future_min_tick,getProductCode,suscribeKline
class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self,tqApi):
        '''初始化设置'''
        super().__init__()
        self.setupUi(self)   #构造Qtdesigner设计的界面
        self.tqApi=tqApi
        self.totalDict={}
        self.thread=None
        self.notificationSoundEnabled=True
        self.checkBox.stateChanged.connect(self.on_sound_toggled)
        # self.pushButton_2.clicked.connect(self.drawKline)
        # self.pushButton.clicked.connect(self.initApi)
        self.pushButton_2.clicked.connect(self.exitUpdate)
        self.tableWidget.cellDoubleClicked.connect(self.on_row_double_click)
        # 创建K线画布 日K
        self.KCanvas_day = KlineCanvas(self.widget_day)
        self.widget_day.setLayout(QVBoxLayout())  # 为widget设置布局
        self.widget_day.layout().addWidget(self.KCanvas_day)  # 添加到widget的布局中
        #  小时K
        self.KCanvas_hour = KlineCanvas(self.widget_hour)
        self.widget_hour.setLayout(QVBoxLayout())  # 为widget设置布局
        self.widget_hour.layout().addWidget(self.KCanvas_hour)  # 添加到widget的布局中
        #15min
        # self.KCanvas_15min = KlineCanvas(self.widget_15min)
        # self.widget_15min.setLayout(QVBoxLayout())  # 为widget设置布局
        # self.widget_15min.layout().addWidget(self.KCanvas_15min) 
        #min
        self.KCanvas_min = KlineCanvas(self.widget_min)
        self.widget_min.setLayout(QVBoxLayout())  # 为widget设置布局
        self.widget_min.layout().addWidget(self.KCanvas_min) 
        self.curTime=''
        self.wait_update_flag=False
        self.initApi()
    def initApi(self):
        IDlist=[
            # 'FG601','OI601','CJ601','MA601',
            # 'PF601','PK601','PX601','SA601','SH601','SM601','SR601',
            # 'TA601','UR601',

            # 'jm2601','p2601','a2601','m2601','y2601','jd2510','lh2511',
            # 'i2601','l2601','v2601','pp2601','eg2601','pg2511','eb2601',
            # 'jd2601',
            # 'al2601','zn2510','rb2601','ao2601',
            # 'ru2601','sp2511','ag2512',

            # 'lc2511','si2511','ps2511',


            'jm2601','lc2511','p2601','si2511','SH601'
                ]#如果一个品种，持仓量最大和成交量最大不是同一个合约，选成交量最大的
        thread_pool=[]
        for index,item in enumerate(IDlist):
            suscribeKline(self.tqApi,self.totalDict,item,index)
        #     t=Thread(target=suscribeKline,args=(self.tqApi,self.totalDict,item))
        #     t.start()
        #     thread_pool.append(t)
        # for t in thread_pool:
        #     t.join()
        print('行情订阅完成')
        self.thread=Thread(target=self.apiUpdate)
        self.thread.start()
    def apiUpdate(self):
        self.wait_update_flag=False
        lastUpdateTime=time()
        updateFreezePeroid=2
        while not self.wait_update_flag:
            self.tqApi.wait_update()
            todeleteItem=[]
            if time()-lastUpdateTime<updateFreezePeroid:continue  #间隔2秒计算一次
            for IntrumentID,productInfo in self.totalDict.items():
                ticks=productInfo['tickObj']
                HMS=nanoseconds_timestamp_to_datetime(ticks.iloc[-1].datetime)
                self.curTime=HMS
                if HMS in ('14:59:59','22:59:59'):
                    print(IntrumentID,'不在开盘时间')
                    todeleteItem.append(IntrumentID)
                    continue
                if not self.tqApi.is_changing(productInfo['K_min']):continue
                # S=int(HMS.split(':')[2])
                # if S%5==0: #用不上一直计算
                res=startegyHandle(productInfo)
                if bool(res):
                    strategyID,msg=res
                    productInfo['alertTimeDict'][strategyID]=time()
                    self.tableHandle(strategyID,msg,productInfo['IntrumentID'])
                

            if bool(todeleteItem):
                for item in todeleteItem:
                    del self.totalDict[item]
            if len(self.totalDict)==0:break
        
        print('退出 waite-update')
    def exitUpdate(self):
        self.wait_update_flag=True
    def on_sound_toggled(self, state):
        """处理复选框状态变化的槽函数"""
        self.notificationSoundEnabled=bool(state == Qt.Checked)
    def tableHandle(self,strategyID,msg,IntrumentID):
        print(strategyID,IntrumentID,msg)
        self.statusbar.showMessage(IntrumentID+msg)
        if self.notificationSoundEnabled:Beep(250,400)
        self.tableWidget.insertRow(0)
        item=QTableWidgetItem(msg)
        self.tableWidget.setItem(0,1,item)
        item=QTableWidgetItem(IntrumentID)
        self.tableWidget.setItem(0,0,item)
        item=QTableWidgetItem(self.curTime)
        self.tableWidget.setItem(0,2,item)
        self.tableWidget.resizeColumnsToContents()
        self.on_row_double_click(0,0)
    def on_row_double_click(self,row, col):
        instrumentID=self.tableWidget.item(row, 0).text()
        self.drawKline(self.totalDict[instrumentID])
    def drawKline(self,productInfo):
        self.KCanvas_day.drawData(productInfo['K_day'].iloc[-30:],'%s-日线'%productInfo['IntrumentID'])
        self.KCanvas_hour.drawData(productInfo['K_h'].iloc[-30:],'%s-小时线'%productInfo['IntrumentID'])
        # self.KCanvas_15min.drawData(productInfo['K_15min'].iloc[-60:],'%s-15分钟线'%productInfo['IntrumentID'])
        self.KCanvas_min.drawData(productInfo['K_min'].iloc[-60:],'%s-1分钟线'%productInfo['IntrumentID'])
    def closeEvent(self, event):
        self.wait_update_flag=True
        self.tqApi.close()
        print('close')
        exit()
if __name__=="__main__":
    # tqApi = TqApi(TqSim(init_balance=100000), auth=TqAuth("cc9200", "091297"))
    tqApi = TqApi(auth=TqAuth("cc9200", "091297"))
    app = QApplication(argv)
    m = MainWindow(tqApi)
    m.show()
    exit(app.exec_())
